package com.huike.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huike.entity.Role;
import com.huike.mapper.RoleMapper;
import com.huike.mapper.RolePermissionMapper;
import com.huike.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
// ctrl + i
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public PageInfo<Role> getPage(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        List<Role> roles = roleMapper.getAll();
        return new PageInfo<>(roles);
    }

    @Override
    public Role getRoleById(Long id) {
        return roleMapper.getRoleById(id);
    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll();
    }

    @Override
    @Transactional
    public void saveOrUpdate(Role role, Long[] permissionIds) {
        // 1.先得到角色id 新增id
        roleMapper.insert(role);

        Long roleId = role.getId();
        // 2. 根据角色id删除对应的所有权限
        rolePermissionMapper.deleteRelations(roleId);

        // 3. 插入现有权限
        if ( permissionIds!=null){
            rolePermissionMapper.insertBatch(roleId,permissionIds);
        }
    }

    @Transactional
    @Override
    public void delete(Long id) {
        roleMapper.deleteById(id);
        // 还需要删除关联关系
        rolePermissionMapper.deleteRelations(id);
    }
}
